package com.fzd.code.captcha.service;

import com.fzd.code.captcha.service.i.ICaptchaManager;
import com.fzd.code.captcha.service.i.IRedisCaptchaService;
import com.fzd.code.captcha.service.i.ISessionCaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

@Service("redis-jcatchap-service")
@Slf4j
public class RedisJCaptchaService implements IRedisCaptchaService {
    public static ImageCaptchaService service = new DefaultManageableImageCaptchaService();

    @Autowired
    private ICaptchaManager captchaManager;

    @Override
    public void create(String id,HttpServletResponse response) throws Exception{
        response.setDateHeader("Expires", 0L);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        BufferedImage bi = service.getImageChallengeForID(id+"-"+captchaManager.key);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    @Override
    public boolean validate(String id,String code) {
        return service.validateResponseForID(id+"-"+captchaManager.key, code);
    }
}
